package com.bitauto.i.commonUtils.test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLock01 {
    Lock lock = new ReentrantLock();

    public void m1() {
        lock.lock();
        try {
            for (int i=0;i<3;i++){
                TimeUnit.SECONDS.sleep(1+i);
                System.out.println(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public void m2() {
        boolean  flag = false;
        try {
            flag=lock.tryLock(5,TimeUnit.SECONDS);
            System.out.println(flag?"获取锁成功":"获取锁失败");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(flag){
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        ReentrantLock rt = new ReentrantLock();
        ReentrantLock01 t = new ReentrantLock01();
        new Thread(t::m1,"t1").start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        new Thread(t::m2,"t2").start();
    }
}
